package com.sti.platform.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aisino.core.server.BaseService;
import com.aisino.tools.util.page.Page;
import com.aisino.tools.util.page.Pagination;
import com.sti.platform.dao.CompanyDao;
import com.sti.platform.dao.UserDao;
import com.sti.platform.model.Company;
import com.sti.platform.model.User;
import com.sti.platform.service.CompanyService;

@Service
public class CompanyServiceImpl extends BaseService implements CompanyService {
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private CompanyDao companyDao;
	
	@Override
	public List<Company> queryList(String params, Integer index, Integer row) {
		StringBuilder builder = new StringBuilder();
		String sql = "SELECT s.*,c.name AS \"parent_unit\" FROM sys_company s"
				+ " LEFT JOIN sys_company c ON s.fjd_id = c.id where 1=1 ";
		builder.append(sql);
		if(params != null && !"".equals(params)){
			builder.append(" and s.name like '%"+params+"%'");
		}
		if(index==null || index==0){//当前页数
			index=1;
		}
		if(row==null || row==0){//每页多少条
			row=10;
		}
		Page page = new Pagination();
		page.setPage(index);
		page.setRow(row);
		return companyDao.queryList(builder.toString(), page);
	}

	@Override
	public void addCompany(Company company) {
		super.save(company);
	}

	@Override
	public void updateCompany(Company company) {
		super.update(company);
	}

	@Override
	public void delectCompany(String companyId) {
		super.remove(Company.class,companyId);
		String sql = "select * from sys_user where company_id = '" + companyId +"'";
		List<User> list = userDao.queryUser(sql);
		for(User li :list){
			li.setCompanyId("");
			super.update(li);
		}
	}

	@Override
	public void delectCompanys(String companyIds) {
		List<String> companys = Arrays.asList(companyIds.split(","));
		if(companys.size()>0){
			for(String company : companys){
				this.delectCompany(company);
			}
		}
	}

	@Override
	public Company queryCompany(String companyId) {
		String sql = "SELECT s.*,c.name AS \"parent_unit\""
				+ " FROM sys_company s"
				+ " LEFT JOIN sys_company c ON s.fjd_id = c.id"
				+ " where s.id = '" + companyId +"'";
		Company company = companyDao.queryCompany(sql).get(0);
		return company;
	}
	
	@Override
	public List<Company> queryCompanys(){
		String sql = "select * from sys_company ";
		List<Company> list = companyDao.queryCompany(sql);
		return list;
	}

}
